package com.cnpc.ds.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cnpc.eisc.base.pojo.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * 自定义填充类
 * 配合@TableField(fill = FieldFill.INSERT)、@TableField(fill = FieldFill.UPDATE)使用
 */
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createDate", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createUser", String.class,  this.getUserId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updateUser", String.class,  this.getUserId());
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }
        return this;
    }

    private String getUserId(){
        try{
            User user =UserResolver.getUser();
            if (Objects.nonNull(user)) {
                String userId = user.getUserId();
                return userId;
            }
        }catch (Exception e){}
        return "";
    }
}
